package com.atguigu.guli.infrastructure.apigateway.filter;

import com.atguigu.guli.service.base.helper.JwtHelper;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("全局过滤器");
        ServerHttpRequest request = exchange.getRequest(); //请求报文请求对象
        String path = request.getURI().getPath(); //获取路径地址

        //谷粒学院api接口，校验用户必须登录
        AntPathMatcher antPathMatcher = new AntPathMatcher(); //路径比较器
        if (antPathMatcher.match("/api/**/auth/**",path)){ //比较
            List<String> tokenList = request.getHeaders().get("token"); //获取请求头中的token

            //没有token
            if (null == tokenList){
                ServerHttpResponse response = exchange.getResponse(); //响应对象
                return out(response);
            }
            boolean b = JwtHelper.checkToken(tokenList.get(0));
            //token校验失败 响应一个R对象的json，内容为需要登录
            if (!b){
                ServerHttpResponse response = exchange.getResponse();
                return out(response);
            }
        }
        //放行
        return chain.filter(exchange);

    }

    //定义当前过滤器的优先级，值越小，优先级越高
    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response){
        //json对象
        JsonObject message = new JsonObject();
        message.addProperty("success", ResultCodeEnum.LOGIN_AUTH.getSuccess());
        message.addProperty("code", ResultCodeEnum.LOGIN_AUTH.getCode());
        message.addProperty("data", "");
        message.addProperty("message",ResultCodeEnum.LOGIN_AUTH.getMessage());
        // buffer缓冲数据流
        DataBuffer buffer = response.bufferFactory().wrap(
                message.toString().getBytes(StandardCharsets.UTF_8));
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        //输出http响应 body代表响应体内容
        return response.writeWith(Mono.just(buffer));
    }
}
